package com.yogee.topseller.fragment.home;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.umeng.analytics.MobclickAgent;
import com.yogee.core.base.HttpFragment;
import com.yogee.core.base.HttpFragment1;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.loading.CustomProgressDialog;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.AnimalUtil;
import com.yogee.core.utils.SharedPreferencesUtils;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.MainActivity;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.login.view.impl.RegisterLabelActivity;
import com.yogee.topseller.activity.persenter.LocationPImpl;
import com.yogee.topseller.activity.persenter.LocationPersenter;
import com.yogee.topseller.activity.view.LocationView;
import com.yogee.topseller.adapter.IntelligentScreeningBigRvAdapter;
import com.yogee.topseller.adapter.IntelligentScreeningListRvAdapter;
import com.yogee.topseller.bean.InterlligentFilterBean;
import com.yogee.topseller.bean.MySelfInfo;
import com.yogee.topseller.bean.ResultBean;
import com.yogee.topseller.fragment.NetDialogFragment;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.interfaces.MyListener;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.utils.LogUtils;
import com.yogee.topseller.utils.RefreshUtil;
import com.yogee.topseller.view.BasicDialog;
import com.yogee.topseller.view.EmptyRecyclerView;
import com.yogee.topseller.view.MySinaRefreshView;
import com.yogee.topseller.view.RefreshView;

import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 智能筛选 || 秒结 fragment
 *
 * @auathor ${XiaoJianghong}
 * @date 2017/6/26.
 */
public class IntelligentScreeningFragment extends HttpFragment1 implements RefreshUtil.OnRefreshListener, LocationView {
    @BindView(R.id.big_img_tv)
    TextView bigImgTv;
    @BindView(R.id.list_tv)
    TextView listTv;
    @BindView(R.id.intelligent_screening_rv)
    EmptyRecyclerView rv;
    Unbinder unbinder;
    @BindView(R.id.refreshLayout)
    TwinklingRefreshLayout refreshLayout;
    @BindView(R.id.refreshLayout1)
    TwinklingRefreshLayout refreshLayout1;
    @BindView(R.id.batch_tv)
    TextView batchTv;
    @BindView(R.id.id_empty_view)
    View id_empty_view;

    
    private IntelligentScreeningBigRvAdapter bigAdapter;//大图适配器
    private IntelligentScreeningListRvAdapter listAdapter;//列表适配器

    private List<InterlligentFilterBean.ProductListBean> bean = new ArrayList<>();
    private boolean isBigImg = false;
    private boolean isLogin;
    private int isMj = 0;
    private LocationPImpl p;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_intelligent_screening;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        isMj = getArguments().getInt("isMj");
        LogUtils.e("ismj","ismj:"+isMj);

        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected void initView() {
        isLogin = AppUtil.isExamine(getActivity());
        MySinaRefreshView headerView = new MySinaRefreshView(getActivity());

        refreshLayout.setOnRefreshListener(new RefreshUtil(this).refreshListenerAdapter());
        refreshLayout.setHeaderView(headerView);
        refreshLayout.setBottomView(new RefreshView(getActivity()));
        refreshLayout.setBottomHeight(50);

        MySinaRefreshView headerView1 = new MySinaRefreshView(getActivity());
        refreshLayout1.setOnRefreshListener(new RefreshUtil(this).refreshListenerAdapter());
        refreshLayout1.setHeaderView(headerView1);
        refreshLayout1.setBottomView(new RefreshView(getActivity()));
        refreshLayout1.setBottomHeight(50);

        bigAdapter = new IntelligentScreeningBigRvAdapter(getActivity());
        listAdapter = new IntelligentScreeningListRvAdapter(getActivity());
        rv.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv.setHasFixedSize(true);
        rv.setAdapter(listAdapter);
        rv.setEmptyView(refreshLayout1);
        if (isMj==0) {
//            if (pd == null)
//                pd = CustomProgressDialog.createDialog(getActivity());
            intelligentFilter("1", "0", "10","0");
            p = new LocationPersenter(this);
            p.initLocation();
            p.startLocation();
            if(AppUtil.isExamine(getActivity())){
                modifyFastQueryLabelIsNull(AppUtil.getUserId(getActivity()));
            }
        } else{
//            batchTv.setVisibility(View.GONE);
            productLable("1", "0", "10");

        }
    }

    @Override
    public void onResume() {
        super.onResume();
//        if(isMj==0)
//            intelligentFilter("1", "0", "10","0");
//        else
//            productLable("1", "0", "10");
    }

    @OnClick({R.id.big_img_tv, R.id.list_tv, R.id.batch_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.big_img_tv:
                isBigImg = true;
                AnimalUtil.QTanEndAnimal(bigImgTv, 500);
                bigImgTv.setBackgroundDrawable(getActivity().getResources().getDrawable(R.drawable.corens_100_style_s));
                listTv.setBackgroundDrawable(getActivity().getResources().getDrawable(R.drawable.corens_100_style_white_bg));
                bigImgTv.setTextColor(Color.parseColor("#ffffff"));
                listTv.setTextColor(getActivity().getResources().getColor(R.color.colorStyle));
                rv.setAdapter(bigAdapter);
                bigAdapter.addData(bean);
                break;
            case R.id.list_tv:
                isBigImg = false;
                AnimalUtil.QTanEndAnimal(listTv, 500);
                bigImgTv.setBackgroundDrawable(getActivity().getResources().getDrawable(R.drawable.corens_100_style_white_bg));
                listTv.setBackgroundDrawable(getActivity().getResources().getDrawable(R.drawable.corens_100_style_s));
                bigImgTv.setTextColor(getActivity().getResources().getColor(R.color.colorStyle));
                listTv.setTextColor(Color.parseColor("#ffffff"));
                rv.setAdapter(listAdapter);
                listAdapter.addData(bean);
                break;
            case R.id.batch_tv:
                intelligentFilter("1", "0", "10", "1");
                break;
        }
    }

    @Override
    public void onRefresh() {//刷新
        if (isMj==0) {
            intelligentFilter("1", "0", "10", "0");
        } else {
            productLable("1", "0", "10");
        }
    }

    @Override
    public void onLoad() {//加载
        if (isMj==0) {
            intelligentFilter("0", String.valueOf(bean.size()), "10", "0");
        } else {
            productLable("0", String.valueOf(bean.size()), "10");
        }
    }

    @Override
    public void loadingFinished() {
        super.loadingFinished();
//        ((MainActivity) getActivity()).dimissPd();
    }

    /**
     * 智能筛选
     * @param isRefresh
     * @param total
     * @param count
     * @param type
     */
    private void intelligentFilter(final String isRefresh, String total, String count, String type) {
        HttpManager.getInstance().intelligentFilter(AppUtil.getUserId(getActivity()), total, count, type).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<InterlligentFilterBean>() {
            @Override
            public void onNext(InterlligentFilterBean o) {
                MySelfInfo.getInstance().setIsPay(o.getIspay());
                if (isRefresh.equals("1")) {
                    if(AppUtil.isExamine(getActivity())){
//                        znsxSuccess
                        MobclickAgent.onEvent(getActivity(), "home_znsx_success");
                    }
                    refreshLayout.finishRefreshing();
                    bean = o.getProductList();
                } else {
                    refreshLayout.finishLoadmore();
                    bean.addAll(o.getProductList());
                }
//                if (isBigImg) {
//                    bigAdapter.addData(bean);
//                } else {
                    listAdapter.addData(bean);
//                }
                if (o.getPopup().equals("1")) {
                    showNormalDialog();
                }
            }
        }, this));
    }
 
    private void rapidBalance(final String isRefresh, String total, String count) {
        HttpManager.getInstance().rapidBalance(AppUtil.getUserId(getActivity()), total, count).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<InterlligentFilterBean>() {
            @Override
            public void onNext(InterlligentFilterBean o) {
                if (isRefresh.equals("1")) {
                    refreshLayout.finishRefreshing();
                    refreshLayout1.finishRefreshing();
                    bean = o.getProductList();
                } else {
                    refreshLayout.finishLoadmore();
                    refreshLayout1.finishLoadmore();
                    bean.addAll(o.getProductList());
                }
                if (isBigImg) {
                    bigAdapter.addData(bean);
                } else {
                    listAdapter.addData(bean);
                }
                
            }
        }, this));
    }

    private void productLable(final String isRefresh, String total, String count){
        String flag = "";
        if(isMj==4){
            flag = "q";
        }else
            flag = isMj-1+"";
        HttpManager.getInstance().productLable(AppUtil.getUserId(getActivity()), total, count,flag).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<InterlligentFilterBean>() {
            @Override
            public void onNext(InterlligentFilterBean o) {
                MySelfInfo.getInstance().setIsPay(o.getIspay());
                if (isRefresh.equals("1")) {
                    refreshLayout.finishRefreshing();
                    bean = o.getProductList();
                } else {
                    refreshLayout.finishLoadmore();
                    bean.addAll(o.getProductList());
                }
                if (isBigImg) {
                    bigAdapter.addData(bean);
                } else {
                    listAdapter.addData(bean);
                }

            }
        }, this));

    }

    private void modifyFastQueryLabelIsNull(String userId){
        HttpManager.getInstance().modifyFastQueryLabelIsNull(userId).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean>() {
            @Override
            public void onNext(ResultBean o) {
                if(o.getResult().equals("1")){
                    SharedPreferencesUtils.put(getActivity(),SharedPreferencesUtils.HAVE_FLASH,true);
                }else{
                    SharedPreferencesUtils.put(getActivity(),SharedPreferencesUtils.HAVE_FLASH,false);
                }
            }
        }, this));
    }
    private void showNormalDialog() {
        BasicDialog.Builder builder = new BasicDialog.Builder(getActivity());
        builder.setMessage("还未选择标签，去选择您所需的标签？")
                .setPositiveButton("确定", new android.app.AlertDialog.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(new Intent(getActivity(), RegisterLabelActivity.class).putExtra("isMain", "1"));
                        dialog.dismiss();
                    }

                })
                .setNegativeButton("取消", new android.app.AlertDialog.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builder.create().show();
    }

    @Override
    public void showMsg(String msg) {

        refreshLayout1.finishRefreshing();
        refreshLayout1.finishLoadmore();
        refreshLayout.finishLoadmore();
        refreshLayout.finishRefreshing();
        super.showMsg(msg);
//        if(msg.equals(ToastUtils.errorMsg)){
//            if(AppUtil.flag){
//                AppUtil.flag = false;
//                NetDialogFragment dialogFragment=new NetDialogFragment();
//
//                dialogFragment.setListener(new MyListener() {
//                    @Override
//                    public void reload() {
//                        onResume();
//                    }
//                });
//                dialogFragment.setArguments(new Bundle());
//                dialogFragment.setCancelable(false);
//                dialogFragment.show(getActivity().getFragmentManager(),"");
//            }
//        }
    }

    @Override
    public void locationError() {

    }

    @Override
    public void onPause() {
        super.onPause();
        if(p!=null)
        p.stopLocation();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(p!=null)
            p.destroyLocation();
    }
}